package com.aorise.controller;

import com.aorise.model.request.UpdatePwdReq;
import com.aorise.model.system.User;
import com.aorise.service.system.UserService;
import com.aorise.utils.MD5Utils;
import com.aorise.utils.StatusDefine;
import com.aorise.utils.StatusDefineMessage;
import com.aorise.utils.json.JsonResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;

/**
 * @Auther: zhouhao
 * @Date: 2019/6/17
 * @Description:
 */
public class BaseController {

    @Autowired
    protected UserService userService;

    protected String getString(@Validated UpdatePwdReq pwd, BindingResult result) {
        if (result.hasErrors()) {
            return JsonResponseData.ofMessage(StatusDefine.DATA_FORMAT_ERROR, result.getFieldError().getDefaultMessage());
        }
        User user = userService.selectByUserId(pwd.getUserId());
        if(user == null){
            return new JsonResponseData(Boolean.FALSE, StatusDefineMessage.GetMessage(StatusDefine.U_INEXISTENCE),
                    StatusDefine.U_INEXISTENCE, "", null).toString();
        }
        if( !(MD5Utils.validPasswd(pwd.getOldPwd(),user.getPassword()))){
            return new JsonResponseData(Boolean.FALSE, StatusDefineMessage.GetMessage(StatusDefine.U_PWD_OLD_FAILED),
                    StatusDefine.U_PWD_OLD_FAILED, "", null).toString();
        }
        if(!(pwd.getNewPwdOne().equals(pwd.getNewPwdTwo()))){
            return new JsonResponseData(Boolean.FALSE, StatusDefineMessage.GetMessage(StatusDefine.U_PWD_TWO_INCONFORMITY),
                    StatusDefine.U_PWD_TWO_INCONFORMITY, "", null).toString();
        }
        if( MD5Utils.validPasswd(pwd.getNewPwdOne(),user.getPassword())){
            return new JsonResponseData(Boolean.FALSE, StatusDefineMessage.GetMessage(StatusDefine.U_PWD_OLD_INCONFORMITY),
                    StatusDefine.U_PWD_OLD_INCONFORMITY, "", null).toString();
        }
        if(userService.changePwdById(pwd.getUserId(),pwd.getNewPwdOne())){
            return  JsonResponseData.ofSuccess(null);
        }
        return null;
    }
}
